import { exec, execSync } from 'child_process';
import * as vscode from 'vscode';

export interface ScanResult {
  file: string;
  line: number;
  message: string;
  ruleId: string;
}

/**
 * 获取当前文件的git diff变更行号
 */
export function getChangedLines(filePath: string): number[] {
  try {
    const diff = execSync(`git diff -U0 ${filePath}`).toString();
    // 解析@@ -old,+new @@结构，提取变更行号
    const changedLines: number[] = [];
    const regex = /@@ \-\d+(,\d+)? \+(\d+)(,(\d+))? @@/g;
    let match;
    while ((match = regex.exec(diff)) !== null) {
      const start = parseInt(match[2], 10);
      const count = match[4] ? parseInt(match[4], 10) : 1;
      for (let i = 0; i < count; i++) {
        changedLines.push(start + i);
      }
    }
    return changedLines;
  } catch (e) {
    vscode.window.showWarningMessage('获取git diff失败，默认全量扫描');
    return [];
  }
}

/**
 * 运行Semgrep扫描，支持可选行号过滤
 */
export function runSemgrepScan(targetFile: string, configPath: string = 'cwe-top-25.yml', onlyLines?: number[]): Promise<ScanResult[]> {
  return new Promise((resolve, reject) => {
    exec(`semgrep --config ${configPath} --json ${targetFile}`, (err, stdout, stderr) => {
      if (err) {
        vscode.window.showErrorMessage('Semgrep扫描失败: ' + stderr);
        return reject(err);
      }
      try {
        const result = JSON.parse(stdout);
        let findings: ScanResult[] = (result.results || []).map((item: any) => ({
          file: item.path,
          line: item.start.line,
          message: item.extra.message,
          ruleId: item.check_id
        }));
        if (onlyLines && onlyLines.length > 0) {
          findings = findings.filter(f => onlyLines.includes(f.line));
        }
        resolve(findings);
      } catch (e) {
        vscode.window.showErrorMessage('解析Semgrep结果失败');
        reject(e);
      }
    });
  });
} 